//
// Created by francklinson on 2021/11/20 AT 11:16.
// May Saint Diana bless you!
//

#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>

using namespace std;

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        vector<string> str;
        int startPos = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (i == s.size() - 1 || s[i + 1] == ' ') {
                str.push_back(s.substr(startPos, i - startPos + 1));
                startPos = i + 2;
            }
        }
        if (pattern.size() != str.size())
            return false;
        unordered_map<char, string> p2s;
        unordered_map<string, char> s2p;
        for (int i = 0; i < pattern.size(); ++i) {
            char x = pattern[i];
            string y = str[i];
            if ((p2s.count(x) && p2s[x] != y) || (s2p.count(y) && s2p[y] != x))
                return false;
            p2s[x] = y;
            s2p[y] = x;
        }
        return true;
    }
};

int main() {
    Solution solution;
    cout << solution.wordPattern("abba", "dog cat cat dog") << endl;
    cout << solution.wordPattern("abba", "dog cat cat fish") << endl;
    cout << solution.wordPattern("aaaa", "dog cat cat dog") << endl;
    cout << solution.wordPattern("abba", "dog dog dog dog") << endl;
    return 0;
}

